package com.qls.consumer.biz.service;

import com.qls.core.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建属于店铺的消息队列
 *
 * @author doyoung
 */
@Service
@Slf4j
public class Queue {

    private static final String[] BASIC_QUEUE_NAMES = {
            Constant.RabbitMq.CALLBACK_HOTEL.getValue(),
            Constant.RabbitMq.CALLBACK_RATES.getValue(),
            Constant.RabbitMq.CALLBACK_RP.getValue(),
            Constant.RabbitMq.INIT.getValue()
    };

    private static final String[] STORE_QUEUE_NAMES = {
            Constant.RabbitMq.RATES.getValue(),
            Constant.RabbitMq.RP.getValue(),
            Constant.RabbitMq.HOTEL.getValue()
    };

    private static final Map<String, Object> ARGS = new HashMap<>();

    static {
        ARGS.put("x-queue-type", "classic");
    }

    @Autowired
    private ConnectionFactory connectionFactory;

    /**
     * 创建基础队列
     */
    public void basic() {
        try {
            for (String queueName : BASIC_QUEUE_NAMES) {
                connectionFactory.createConnection().createChannel(false).queueDeclare(queueName, true, false, false, ARGS);
                connectionFactory.createConnection().createChannel(false).queueBind(queueName, Constant.RabbitMq.HOTEL_EXCHANGE.getValue(), queueName);
            }
        } catch (IOException ignored) {
        }
    }

    /**
     * 创建队列
     *
     * @param storeId Integer
     * @return boolean
     */
    public boolean create(Integer storeId) {
        try {
            for (String queueName : STORE_QUEUE_NAMES) {
                queueName = storeId + "_" + queueName;
                connectionFactory.createConnection().createChannel(false).queueDeclare(queueName, true, false, false, ARGS);
                connectionFactory.createConnection().createChannel(false).queueBind(queueName, Constant.RabbitMq.HOTEL_EXCHANGE.getValue(), queueName);
            }
        } catch (IOException ignored) {
            return false;
        }
        return true;
    }

    /**
     * 销毁队列
     *
     * @param storeId Integer
     * @return boolean
     */
    public boolean destroy(Integer storeId) {
        try {
            for (String queueName : STORE_QUEUE_NAMES) {
                queueName = storeId + "_" + queueName;
                connectionFactory.createConnection().createChannel(false).queueDelete(queueName);
            }
        } catch (IOException ignored) {
            return false;
        }
        return true;
    }

}
